/**
 * Copyright (C), 2021-2023, 四信物联网有限公司
 * FileName: BeiDouDecoder
 * Author:   Chapin
 * Date:     2023/10/11 16:05
 * Description: 北斗3.0协议解码器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.fourfaith.iot.beidou.decodec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * 〈北斗3.0协议解码器〉
 * @author Chapin
 * @create 2023/10/11
 * @since 1.0.0
 */
@Slf4j
public class BeiDouFrameDecoder extends LineBasedFrameDecoder {
    public BeiDouFrameDecoder(int maxLength) {
        super(maxLength);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
        ByteBuf decode = (ByteBuf)super.decode(ctx, buffer);
        if(decode != null){
            try {
                // 根据换行符解码，获取北斗报文，无效日志丢弃
                String decodeStr = decode.toString(StandardCharsets.US_ASCII);
                if(decodeStr.contains(BeiDouContants.head) && decodeStr.contains(BeiDouContants.checkFlag)){
                    decodeStr = decodeStr.substring(decodeStr.indexOf(BeiDouContants.head));
                    if(decodeStr.length() > 6){
                        log.info("北斗报文ASCII解码结果：{}",decodeStr);
                        return decode;
                    }
                }else {
    //                log.info("北斗报文ASCII解码无效数据：{}",decodeStr);
                }
            } catch (Exception e) {
                log.error("北斗报文ASCII解码异常",e);
                // 在流水线处理的过程中，如果某个处理器将原始ByteBuf转换为其它类型的Java对象，这时ByteBuf就没用了，必须调用release手动释放
                ReferenceCountUtil.release(buffer);
            }
        }
        return null;
    }
}